<?php

namespace App\Listeners\Plane;

use App\Events\Plane\PlaneTicketQueryEvent;
use App\Models\Trip\History\Repositories\Interfaces\TripQueryHistoryRepositoryInterface;
use App\Trip\Orders\TripType;

class PlaneTicketQueryListener
{
    private $repo;

    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        $this->repo = app(TripQueryHistoryRepositoryInterface::class);
    }

    /**
     * Handle the event.
     *
     * @param object $event
     * @return void
     */
    public function handle(PlaneTicketQueryEvent $event)
    {
        $data = $event->data;
        if (!isset($data['user'])) {
            return;
        }

        $user_id = $data['user']->getUserId() ?: '';
        $from    = $data['from'];
        $to      = $data['to'];
        if ($user_id) {
            // 添加到历史记录
            $this->repo->addByUserId($user_id, [
                'trip_type'  => TripType::TRIP_TYPE_PLANE,
                'from_type'  => $from['type'],
                'to_type'    => $to['type'],
                'from_code'  => $from['code'],
                'to_code'    => $to['code'],
                'updated_at' => $data['updated_at'] ?? '',
            ]);
        }
    }
}
